#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <cstring>

void Usage(const std::string &proc)
{
    std::cout <<"Usage\n\t" << proc << "serve_ip serve_port"<<std::endl;
}
int main(int argc,char** argv)
{
    if(argc!=3)
    {
        Usage(argv[0]);
        return 2;
    }
    std::string serveip =argv[1];
    uint16_t serveport = std::stoi(argv[2]);

    // 创建socket
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "sock fail:" << errno << std::endl;
        return 1;
    }
    // 客户端其实也要绑定，不过不需要显示bind
    std::cout << "create sucessful:" << sock << std::endl;
    struct sockaddr_in serve;
    memset(&serve,0,sizeof(serve));
    serve.sin_family = AF_INET;//ip
    serve.sin_port = htons(serveport);//端口号
    serve.sin_addr.s_addr = inet_addr(serveip.c_str());//转换为网络序列
    while (true)
    {
        std::string inbuffer;
        std::cout << "please enter:";
        std::getline(std::cin, inbuffer);
        //std::cout << inbuffer << std::endl;

        ssize_t n = sendto(sock,inbuffer.c_str(),inbuffer.size(),0,(struct sockaddr*)&serve,sizeof(serve));
        if(n > 0)
        {
            //收消息
            char buffer[1024];
            struct sockaddr_in tmp;
            socklen_t len = sizeof(tmp);
            ssize_t m = recvfrom(sock,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&tmp,&len);
            if(m >0)
            {
                buffer[m] = 0;
                std::cout << "server echo:" << buffer << std::endl;
                //buffer[m] = 0;
            }
            else
                break;
        }
        else
            break;
    }
    close(sock);
    return 0;
}